package com.xc.controller;

import com.alibaba.fastjson.JSONObject;
import com.xc.dto.ResultDTO;
import com.xc.entity.UserEntity;
import com.xc.service.UserService;
import com.xc.util.AesCbcUtil;
import com.xc.util.JSONCopy;
import com.xc.vo.WeiXinPhoneVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

@RestController
@Api(tags = "微信小程序登录")
public class WxLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.grant_type}")
    private String grant_type;
    @Value("${wx.secret}")
    private String secret;

    @GetMapping("/wx")
    @ApiOperation("根据当前手机号查询，如果有，则直接登录，没有则新增一条数据")
    public ResultDTO login(WeiXinPhoneVO weiXinPhoneVO) throws Exception {

        String phone = aa(weiXinPhoneVO);

        UserEntity userEntity = UserEntity.builder()
                .password("123456")
                .username(JSONCopy.getKey(phone, "phoneNumber"))
                .phone(JSONCopy.getKey(phone, "phoneNumber"))
                .enable(1)
                .build();

        return userService.login(userEntity);
    }

    public String aa(WeiXinPhoneVO weiXinPhoneVO) throws Exception {
        String encryptedData = weiXinPhoneVO.getEncryptedData();
        String iv = weiXinPhoneVO.getIv();
        String urlNameString = "https://api.weixin.qq.com/sns/jscode2session?access_token=ACCESS_TOKEN&js_code=" + weiXinPhoneVO.getCode();
        urlNameString += "&iv=" + iv;
        urlNameString += "&appId=" + appId;
        urlNameString += "&encryptedData=" + encryptedData;
        urlNameString += "&grant_type=" + grant_type;
        urlNameString += "&secret=" + secret;
        URL realUrl = new URL(urlNameString);
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立实际的连接
        connection.connect();

        BufferedReader in = null;
        String result = "";
        in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String session_key = jsonObject.getString("session_key");
//        String openid= jsonObject.getString("openid");
        return AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
    }

    @GetMapping("/getPhoneNum")
    @ApiOperation("直接返回手机号")
    public ResultDTO getPhoneNum(WeiXinPhoneVO weiXinPhoneEntity) throws Exception {
        String encryptedData = weiXinPhoneEntity.getEncryptedData();
        String iv = weiXinPhoneEntity.getIv();
        String urlNameString = "https://api.weixin.qq.com/sns/jscode2session?access_token=ACCESS_TOKEN&js_code=" + weiXinPhoneEntity.getCode();
        urlNameString += "&iv=" + iv;
        urlNameString += "&appId=" + appId;
        urlNameString += "&encryptedData=" + encryptedData;
        urlNameString += "&grant_type=" + grant_type;
        urlNameString += "&secret=" + secret;
        URL realUrl = new URL(urlNameString);
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立实际的连接
        connection.connect();

        BufferedReader in = null;
        String result = "";
        in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String session_key = jsonObject.getString("session_key");
//        String openid= jsonObject.getString("openid");
//        return AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
        return ResultDTO.data(AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8"));
    }


}
